<template>
  <t-dialog v-if="editOpen" :header="header" @confirm="onSubmit" :visible.sync="visible" :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }" :onClose="closeDialog" :closeOnOverlayClick="false"
            width="80%"
            top="5%">
    <div style="height: 65vh;">
      <t-form ref="form" :colon="true" :data="formData" labelWidth="100px" :rules="rules">
        <t-form-item label="所属年度" name="year">
          <t-date-picker v-model="formData.year" mode="year" clearable/>
        </t-form-item>
        <t-form-item label="奖项列表" label-align="top" name="awardsInfoList">
          <div>
            <t-table
              rowKey="id"
              :data="formData.awardsInfoList"
              :columns="columns"
              bordered
              hover
              :selected-row-keys="selectedRowKeys"
              @select-change="(val)=>{selectedRowKeys=val}"
            >
              <template #id="{rowIndex}">
                {{ rowIndex + 1 }}
              </template>
              <template #name="{row}">
                <t-select clearable v-model="row.awardsLevel" @change="(val,content)=>{ row.name=content.option.label }"
                          :options="dict.type.wcx_awards_level"></t-select>
              </template>
              <template  #awardsNum="{row}">
                <t-input-adornment  style="justify-content: center" append="项">
                  <t-input-number
                    :disabled="row.awardsLevel === '99'"
                    @keyup="()=>{if(row.awardsNum){row.awardsNum=Number((row.awardsNum || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                    :allowInputOverLimit="false" clearable
                    v-model="row.awardsNum"
                    theme="normal"
                    :min="0"></t-input-number>
                </t-input-adornment>
              </template>
              <template #awardsAmount="{row}">
                <t-input-adornment style="justify-content: center" append="万元">
                  <t-input-number :disabled="row.awardsLevel === '99'" :decimal-places="2"
                                  @keyup="()=>{if(row.awardsAmount){row.awardsAmount=Number((row.awardsAmount || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="row.awardsAmount"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </template>
            </t-table>
            <div style="margin-top: 10px" class="btn-group-inline">
              <t-button @click="addData">新增</t-button>
              <t-button @click="upData">上移</t-button>
              <t-button @click="downData">下移</t-button>
              <t-button @click="delData">删除</t-button>
            </div>
          </div>
        </t-form-item>
        <t-row style="font-size: 20px;font-weight: bold">
          <t-col :span="6">
            <t-form-item label="总奖项">
              {{ awardsAllNum }}项
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总奖金">
              {{ awardsAllAmount }}万元
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </t-dialog>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    :confirmBtn="null"
    width="60%"
    top="5%"
    v-else
  >
    <div style="height: 65vh;">
      <t-form ref="form" :colon="true" :data="formData" labelWidth="100px" :rules="rules">
        <t-form-item label="所属年度" name="year">
          <t-date-picker v-model="formData.year" mode="year" clearable/>
        </t-form-item>
        <t-form-item label="奖项列表" label-align="top" name="awardsInfoList">
          <div>
            <t-table
              rowKey="id"
              :data="formData.awardsInfoList"
              :columns="columns"
              bordered
              hover
              :selected-row-keys="selectedRowKeys"
              @select-change="(val)=>{selectedRowKeys=val}"
            >
              <template #id="{rowIndex}">
                {{ rowIndex + 1 }}
              </template>
              <template #name="{row}">
                {{ row.awardsLevel | filterByDict(dict.type.wcx_awards_level) }}
              </template>
              <template  #awardsNum="{row}">
                {{ row.awardsNum }}项
              </template>
              <template #awardsAmount="{row}">
                {{ row.awardsAmount }}万元
              </template>
            </t-table>
          </div>
        </t-form-item>
        <t-row style="font-size: 20px;font-weight: bold">
          <t-col :span="6">
            <t-form-item label="总奖项">
              {{ awardsAllNum }}项
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总奖金">
              {{ awardsAllAmount }}万元
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </t-dialog>
</template>

<script>
import dayjs from 'dayjs';

export default {
  name: "add-edit-year-innovation-award",
  dicts: ['wcx_awards_level'],
  props: {
    objId: {
      type: Number,
      default: 0
    },
    header: {
      type: String,
      default: '',
    },
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      visible: true,
      loading: false,
      selectedRowKeys: [],
      awardsAllNum: 0,
      awardsAllAmount: 0,
      formData: {
        year: dayjs().year().toString(),
        oneAwardsNum: 0,
        oneAwardsAmount: 0,
        twoAwardsNum: 0,
        twoAwardsAmount: 0,
        threeAwardsNum: 0,
        threeAwardsAmount: 0,
        awardsInfoList: []
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 100
        },
        {
          colKey: "name",
          title: "奖项名称",
          align: "center",
        },
        {
          colKey: "awardsNum",
          title: "奖项个数",
          align: "center",
        },
        {
          colKey: "awardsAmount",
          title: "每项奖金",
          align: "center",
        },
        {
          colKey: "useAwardsNum",
          title: "已分配奖项数量",
          align: "center",
        },
      ],
      rules: {
        year: [{required: true, message: "所属年度不能为空"}],
        awardsInfoList: [{required: true, validator: (val) => val.length > 0, message: "奖项列表不能为空", type: "error"}],
      }
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    "formData.awardsInfoList": {
      immediate: true,
      handler(val) {
        let awardsAllNum = 0
        let awardsAllAmount = 0
        val.forEach(item => {
          awardsAllNum += item.awardsNum || 0;
          awardsAllAmount += item.awardsAmount || 0;
        })
        this.awardsAllNum = awardsAllNum || 0;
        this.awardsAllAmount = awardsAllAmount || 0;
      },
      deep: true
    }
  },
  methods: {
    getObj() {
      this.$api.wcx.apply.annualAwardsGet(this.objId).then(response => {
        this.formData = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.formData.awardsInfoList.every((val, index) => {
            const tag = "奖项列表";
            if (val.name === "") {
              this.$message.error(`${tag}：第${index + 1}条"奖项名称"不能为空`);
              return false;
            }
            return true;
          });
          if (!isValidate) {
            return false
          }
          this.formData.awardsInfoList.forEach((val, index) => {
            this.formData.awardsInfoList[index].sort = index + 1;
          });
          this.loading = true;
          if (this.objId) {
            this.$api.wcx.apply.annualAwardsUpdate(this.formData).then(response => {
              this.loading = false;
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.wcx.apply.annualAwardsAdd(this.formData).then(response => {
              this.loading = false;
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }

        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    addData() {
      this.formData.awardsInfoList.push({
        id: Date.parse(new Date()),
        name: "",
        awardsLevel: '',
        awardsNum: 0,
        awardsAmount: 0
      });
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.formData.awardsInfoList[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.formData.awardsInfoList.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.formData.awardsInfoList, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.formData.awardsInfoList[this.formData.awardsInfoList.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.formData.awardsInfoList.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.formData.awardsInfoList, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.formData.awardsInfoList.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.formData.awardsInfoList.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
.t-row {
  margin-bottom: 24px;
}
</style>
